package com.yuyi.tool;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.util.StringUtils;

public class MD5Tool {
	/**
	 * 对字符串进行Md5加密
	 * 
	 * @param input
	 *            原文
	 * @return md5后的密文
	 */
	public static String md5(String input) {
		byte[] code = null;
		try {
			code = MessageDigest.getInstance("md5").digest(input.getBytes());
		} catch (NoSuchAlgorithmException e) {
			code = input.getBytes();
		}
		BigInteger bi = new BigInteger(code);
		return bi.abs().toString(32).toUpperCase();
	}

	/**
	 * 对字符串进行Md5加密
	 * 
	 * @param input
	 *            原文
	 * @param salt
	 *            随机数
	 * @return string
	 */
	public static String generatePasswordMD5(String input, String salt) {
		if (StringUtils.isEmpty(salt)) {
			salt = "";
		}
		return md5(salt + md5(input));
	}
	
	/**
     * 对字符串进行Md5加密
     * 
     * @param input
     *            原文
     * @return md5后的密文
     */
    public static String md51(String input) {
        byte[] code = null;
        try {
            code = MessageDigest.getInstance("md5").digest(input.getBytes());
        } catch (NoSuchAlgorithmException e) {
            code = input.getBytes();
        }
        BigInteger bi = new BigInteger(code);
        return bi.abs().toString(32).toUpperCase();
    }

    /**
     * 对字符串进行Md5加密
     * 
     * @param input
     *            原文
     * @param salt
     *            随机数
     * @return string
     */
    public static String generatePasswordMD51(String input, String salt) {
        if (StringUtils.isEmpty(salt)) {
            salt = "";
        }
        return md5(salt + md5(input));
    }
    
    private static final String SALT = "yuyigufen";

    private static final String ALGORITH_NAME = "md5";

    private static final int HASH_ITERATIONS = 2;

    public static String encrypt(String pswd) {
        String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(SALT), HASH_ITERATIONS).toHex();
        return newPassword;
    }

    public static String encrypt(String username, String pswd) {
        String newPassword = new SimpleHash(ALGORITH_NAME, pswd, ByteSource.Util.bytes(username+SALT),
                HASH_ITERATIONS).toHex();
        return newPassword;
    }
    public static void main(String[] args) { 
             System.out.println(encrypt("3008","123456")); 
    }
}
